package com.hzb.LNReader;

import java.io.File;
import java.text.DateFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.AdapterView.OnItemClickListener;

public class ShowHistoryActivity extends Activity {
	static SimpleDateFormat format;
	static final String[] from = new String[] {"fileName", "lastRead", "process", "summary"};
	static final int[] to = new int[] {R.id.historyFileName, R.id.historyLastRead, R.id.historyProcess, R.id.historySummary};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if (format == null) {
			format = new SimpleDateFormat("M-d h:m a");
			DateFormatSymbols symbols = format.getDateFormatSymbols();
			symbols.setAmPmStrings(new String[] {"AM", "PM"});
			format.setDateFormatSymbols(symbols);
		}
		
		ListView historyView = new ListView(this);
		ReadHistory iter = ReaderContext.head;
		String rootpath = ReaderContext.rootFolder;
		int rootLen = rootpath.length();
		ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String,Object>>();
		for (;iter != null; iter = iter.next) {
			if (!iter.file.isFile()) {
				iter.remove();
				continue;
			}
			HashMap<String, Object> entry = new HashMap<String, Object>(6);
			File file = iter.file;
			String filename = file.getAbsolutePath();
			if (filename.startsWith(rootpath)) filename = filename.substring(rootLen);
			entry.put("fileName", filename);
			entry.put("lastRead", format.format(new Date(iter.lastReadTime)));
			entry.put("process", iter.process);
			entry.put("summary", iter.summary);
			entry.put("record", iter);
			list.add(entry);
		}
		SimpleAdapter adapter = new SimpleAdapter(this, list, R.layout.historyitem, from, to);
		historyView.setAdapter(adapter);
		
		historyView.setClickable(true);
		historyView.setOnItemClickListener(new OnItemClickListener() {

			@SuppressWarnings("unchecked")
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				HashMap<String, Object> entry = (HashMap<String, Object>) parent.getItemAtPosition(position);
				ReadHistory history = (ReadHistory) entry.get("record");
				history.offer();
				openReader();
			}
		});
		setContentView(historyView);
	}
	
	@Override
	public void onBackPressed() {
		super.onBackPressed();
		openReader();
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		finish();
	}
	
	void openReader() {
		Intent intent = new Intent(this, ReaderActivity.class);
		startActivity(intent);
		finish();
	}
}
